<script setup>
import FormItemSearch from '@/components/form/FormItemSearch.vue'
import TableColumnIndex from '@/components/table/TableColumnIndex.vue'
import { usePagination, useRequest, useDialog } from '@/hooks'
import { deviceApi, userListApi } from '@/api'
import DeviceFormDialog from './DeviceFormDialog.vue'
import RemoteLinkDialog from './RemoteLinkDialog.vue'
import { ElMessageBox } from 'element-plus'

const STATUS = ['离线', '在线']
const STATUS_COLORS = ['text-danger', 'text-success']

const DEVICE_TYPE = [
  {
    label: '通用',
    value: 1
  }
]

const title = computed(() => useRoute().meta.title ?? '设备列表')

const form = ref({
  deviceId: '',
  deviceStatus: '',
  deviceType: ''
})
const formRef = ref()
function reset() {
  formRef.value.resetFields()
  search()
}

const { pageSize, currentPage, pageSizes } = usePagination({
  onChange: () => refresh()
})

const { refresh, data, count } = useRequest(deviceApi.pageDeviceList, {
  initialData: [],
  immediate: true,
  params: () => ({
    ...form.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value
  })
})

function search() {
  currentPage.value = 1
  refresh()
}

const active = ref(null)
const { visible, open } = useDialog(active)

async function handleSubmit(formValue) {
  if (active.value) {
    await deviceApi.updateDevice({ ...formValue, id: active.value.id })
  } else {
    await deviceApi.addDevice(formValue)
  }
  ElMessage.success('操作成功')
  visible.value = false
  refresh()
}

const { visible: remoteLinkVisible, open: remoteLinkOpen } = useDialog(active)

async function remoteLinkSubmit(params) {
  await deviceApi.updateRemoteUrl({
    id: active.value.id,
    remoteUrl: params.remoteUrl
  })
  ElMessage.success('操作成功')
  remoteLinkVisible.value = false
  refresh()
}

const { data: accounts } = useRequest(userListApi.selectAnchorLogin, {
  immediate: true,
  initialData: []
})

async function handleRemove(row) {
  await ElMessageBox.confirm('此操作将删除该设备, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await userListApi.deleteStatus({ ids: [row.id] })
  ElMessage.success('删除成功')
  refresh()
}
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header> {{ title }} </template>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
        label-suffix="："
        label-position="left"
        @submit.prevent="search"
      >
        <el-row :gutter="20">
          <FormItemSearch label="设备ID" prop="deviceId">
            <el-input v-model.trim="form.deviceId" clearable />
          </FormItemSearch>
          <!-- <FormItemSearch label="所属账号" prop="phone">
            <el-select v-model="form.phone" filterable clearable>
              <el-option
                v-for="item in accounts"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </FormItemSearch> -->
          <FormItemSearch label="在线状态" prop="deviceStatus">
            <el-select v-model="form.deviceStatus" filterable clearable>
              <el-option
                v-for="(item, index) in STATUS"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </FormItemSearch>
          <FormItemSearch label="设备类型" prop="deviceType">
            <el-select v-model="form.deviceType" filterable clearable>
              <el-option
                v-for="item in DEVICE_TYPE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </FormItemSearch>
        </el-row>

        <el-button type="primary" native-type="submit" @submit="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="open()"> 新增 </el-button>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <el-table :data="data" style="width: 100%">
        <TableColumnIndex :page="currentPage" :page-size="pageSize" />
        <el-table-column prop="deviceId" label="设备ID" />
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column
          prop="deviceType"
          label="设备类型"
          :formatter="
            row =>
              DEVICE_TYPE.find(item => item.value === row.deviceType)?.label
          "
        />
        <el-table-column prop="deviceMac" label="MAC地址" />
        <el-table-column prop="deviceStatus" label="在线状态">
          <template #default="{ row }">
            <span
              v-if="STATUS[row.deviceStatus]"
              :class="STATUS_COLORS[row.deviceStatus]"
            >
              {{ STATUS[row.deviceStatus] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="赛事列表" />
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="remoteLinkOpen(row)">
              链接
            </el-button>
            <el-button link type="primary" @click="open(row)"> 编辑 </el-button>
            <el-button link type="danger" @click="handleRemove(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        hide-on-single-page
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="mt-4 justify-end"
        small
      />
    </el-card>

    <DeviceFormDialog
      v-model="visible"
      :title="active ? '编辑设备' : '新增设备'"
      :detail="active"
      :accounts="accounts"
      @submit="handleSubmit"
    />

    <RemoteLinkDialog
      v-model="remoteLinkVisible"
      :title="active?.remoteUrl ? '编辑远程链接' : '新增远程链接'"
      :detail="active"
      @submit="remoteLinkSubmit"
    />
  </div>
</template>
